<?php
namespace Home\Controller;

use Think\Controller;

class UserController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 用户信息
     * @return [type] [description]
     */
    public function info()
    {
        $user = M('user')->field('*')->find(USER_ID);

        success($user);
    }

    /**
     * 提现申请
     * @return [type] [description]
     */
    public function withdrawApply()
    {
        $money = I('post.money', 0.00, 'floatval');
        if ($money < 1) {
            error(6020, '提现金额最少为一元');
        }

        $data = [
            'user_id'  => USER_ID,
            'order_no' => generation_withdraw_order_no(USER_ID),
            'money'    => $money,
            'status'   => 1,
            'add_time' => CUR_DATETIME,
        ];
        $id = M('withdraw')->add($data);

        // 自动提现金额
        setting('auto_withdraw_money', 50);
        $auto_withdraw_money = setting('auto_withdraw_money');

        error(6023, '提现成功，约1天内到账');

        $is_auto = $money >= $auto_withdraw_money ? false : true;
        if ($is_auto) {

            $result = D('Wechat', 'Service')->withdraw($id);
            if ($result) {
                success([]);
            } else {
                error(6022, '提现失败');
            }

        } else {
            error(6021, '提现金额超过' . $auto_withdraw_money . '元需平台审核，预计1-3个小时内到账');
        }

    }

    /**
     * 用户提现
     * @return [type] [description]
     */
    public function withdraw()
    {
        $this->display();
    }

    public function login()
    {
        Vendor('Wechat/Wechat');

        // debug
        $wechat = new \Wechat(C('WX_CONF'));

        $access = $wechat->getOauthAccessToken();

        $info = $wechat->getOauthUserinfo($access['access_token'], $access['openid']);

        D('User', 'Service')->login(2, $info);

        $refer = session('?refer') ? session('refer') : U('red/send');
        redirect($refer);
    }
}
